<template>
  <div>
    <a-list
      itemLayout="horizontal"
      :dataSource="list">
      <a-list-item slot="renderItem" slot-scope="item, index" :key="index">
        <a-list-item-meta>
          <a slot="title">{{ item.title }}</a>
          <span slot="description">
            <span>{{ item.description }}</span>
            <span v-if="item.value"> : </span>
            <span >{{ item.value }}</span>
          </span>
        </a-list-item-meta>
        <template v-if="item.actions">
          <a slot="actions" @click="item.actions.callback(item.title)">{{ item.actions.title }}</a>
        </template>
      </a-list-item>
    </a-list>

    <a-modal
      :title="modal.title"
      centered
      :visible="modal.visible"
      width="400px"
      @cancel="cancelModal"
      @ok="okModal">
      <div v-if="modal.title === '账号密码'"><a-input-password placeholder="input new password" v-model="modal.password"/></div>
      <div v-else><a-input placeholder="input new email" v-model="modal.email"/></div>
    </a-modal>
  </div>
</template>

<script>
import { editUser } from '@/api/userManage'
export default {
name: 'SecuritySetting',
data () {
  return {
    modal: {
      title: '',
      visible: false,
      password: null,
      email: null
    },
    userInfo: this.$store.getters.userInfo
  }
},

computed: {
    list () {
      return [
        { title: '账号密码', description: '当前密码强度', value: '强', actions: { title: '修改', callback: this.showModal } },
        { title: '邮箱', description: '已绑定邮箱', value: this.userInfo.email, actions: { title: '修改', callback: this.showModal } }
      ]
    }
  },
  methods: {
    showModal (title) {
      this.modal.title = title
      this.modal.visible = true
    },
    cancelModal () {
      this.modal.visible = false
    },
    okModal () {
      if (this.modal.title === '账号密码') {
        if (this.modal.password) {
          editUser({
            id: this.userInfo.id,
            password: this.modal.password
          })
          .then(res => {
            this.$message.success('密码修改成功')
          })
          .catch(err => {
            this.$message.error(err.response.data.msg || '密码修改失败')
          })
        } else {
          this.$message.info('请先填写')
        }
      } else {
        if (this.modal.email) {
          editUser({
            id: this.userInfo.id,
            email: this.modal.email
          })
          .then(res => {
            this.$message.success('邮箱修改成功')
          })
          .catch(err => {
            this.$message.error(err.response.data.msg || '邮箱修改失败')
          })
        } else {
          this.$message.info('请先填写')
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>
